package com.tencent.sr.iris.activity.service.activity.impl;

import com.google.common.collect.Maps;
import com.tencent.sr.iris.activity.common.util.AssertUtils;
import com.tencent.sr.iris.activity.interfaces.enums.ActivityIdEnum;
import com.tencent.sr.iris.activity.interfaces.request.acticity.BatchDataRequest;
import com.tencent.sr.iris.activity.interfaces.response.activity.BatchStatisticsResponse;
import com.tencent.sr.iris.activity.service.activity.BatchDataStatisticsHandler;
import com.tencent.sr.rmall.common.exception.TMallBizException;
import com.tencent.sr.rmall.common.exception.code.BaseErrorCode;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;

@Service
public class BatchDataStatisticsService {

    @Resource
    private Map<String, BatchDataStatisticsHandler> handlerMap = Maps.newHashMap();

    @Resource
    private List<BatchDataStatisticsHandler> handlers;

    @PostConstruct
    public void init() {
        for (BatchDataStatisticsHandler handler : handlers) {
            for (String activityId : handler.supportedActivityIds()) {
                BatchDataStatisticsHandler statisticsHandler = handlerMap.get(activityId);
                AssertUtils.isNull(statisticsHandler, BaseErrorCode.SYSTEM_ERROR);

                handlerMap.put(activityId, handler);
            }
        }
    }

    /**
     * 统计
     *
     * @param batchDataRequest
     * @return
     */
    public BatchStatisticsResponse activityStatic(BatchDataRequest batchDataRequest) {
        ActivityIdEnum activityId = batchDataRequest.getActivityId();

        Supplier<TMallBizException> supplier = () -> new TMallBizException(
                String.format("暂不支持%s的统计", activityId.getDesc()));
        BatchDataStatisticsHandler statisticsHandler = Optional.ofNullable(handlerMap.get(activityId.getCode()))
                .orElseThrow(supplier);

        return statisticsHandler.statistics(batchDataRequest);
    }
}
